package online.yysh.charging;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;

import online.yysh.charging.base.BaseActivity;
import online.yysh.charging.bean.WithdrawalRecord;
import online.yysh.charging.bean.request.CancelApplyBackRequest;
import online.yysh.charging.bean.response.GetWithdrawalRecordResponse;
import online.yysh.charging.utils.HttpUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 提现记录
 */
public class WithdrawalRecordActivity extends BaseActivity {

    private TextView tv_cancel, tv_title;
    private RecyclerView rv;
    private MyAdapter adapter;

    private List<WithdrawalRecord> withdrawalRecordList = new ArrayList<>();

    private static final int QUERY_ORDER_SUCCEED = 200;
    private static final int QUERY_ORDER_FAILED = 201;
    private static final int CANCEL_ORDER_FAILED = 202;
    private static final int CANCEL_ORDER_SUCCEED = 203;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case QUERY_ORDER_SUCCEED:
                    adapter.notifyDataSetChanged();
                    break;
                case QUERY_ORDER_FAILED:
                    showToast("查询提现订单失败");
                    break;
                case CANCEL_ORDER_FAILED:
                    showToast("取消提现失败");
                    break;
                case CANCEL_ORDER_SUCCEED:
                    showToast("取消提现成功");
                    getWithdrawalRecord();
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_record;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        rv = findViewById(R.id.rv_record);

        tv_cancel = findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_title = findViewById(R.id.tv_title);
        tv_title.setText(R.string.withdrawal_history);
    }

    @Override
    protected void initData() {
        getWithdrawalRecord();
        rv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyAdapter();
        rv.setAdapter(adapter);
    }

    /**
     * 获取提现记录
     */
    private void getWithdrawalRecord() {
        HttpUtil.getInstance().getWithdrawalRecord(openid, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(QUERY_ORDER_FAILED);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                logE("getWithdrawalRecord:"+result);
                if (result.contains("ok")){
                    GetWithdrawalRecordResponse getWithdrawalRecordResponse = new Gson().fromJson(result, GetWithdrawalRecordResponse.class);
                    if ("ok".equals(getWithdrawalRecordResponse.getStatus())){
                        withdrawalRecordList = getWithdrawalRecordResponse.getData();
                        handler.sendEmptyMessage(QUERY_ORDER_SUCCEED);
                    }else{
                        handler.sendEmptyMessage(QUERY_ORDER_FAILED);
                    }
                }else{
                    handler.sendEmptyMessage(QUERY_ORDER_FAILED);
                }
            }
        });
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        @NonNull
        @Override
        public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_withdrawal_record, parent, false);
            return new MyAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {
            final WithdrawalRecord record = withdrawalRecordList.get(position);
            String createTime = record.getCreatetime();
            holder.tv_time.setText("提现时间：" + createTime.replace("T"," ").substring(0,createTime.length()-4));
            String status = record.getStatus();
            if ("0".equals(status)) {
                status = "取消提现";
            } else if ("1".equals(status)) {
                status = "申请提现";
            } else if ("2".equals(status)) {
                status = "已提现";
            } else if ("3".equals(status)) {
                status = "拒绝提现";
            } else {
                status = "待商家确认";
            }
            holder.tv_status.setText("提现状态：" + status);
            holder.tv_money.setText("提现金额(元)：" + record.getMoney());
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if ("1".equals(record.getStatus()) || "4".equals(record.getStatus())){
                        showCancelApplyBackDialog(record);
                    }else{
                        showToast("该提现单已结束");
                    }
                    return true;
                }
            });
        }

        @Override
        public int getItemCount() {
            return withdrawalRecordList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv_time, tv_status, tv_money;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_status = itemView.findViewById(R.id.tv_status);
                tv_money = itemView.findViewById(R.id.tv_money);
            }
        }
    }

    /**
     * 取消提现弹窗
     * @param record
     */
    private void showCancelApplyBackDialog(final WithdrawalRecord record) {
        final AppCompatDialog appCompatDialog = new AppCompatDialog(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_cancel_appaly_bacl, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatDialog.dismiss();
            }
        });
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelApplyBack(record);
                appCompatDialog.dismiss();

            }
        });
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setGravity(Gravity.CENTER);
        window.setLayout(700, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }

    /**
     * 取消申请提现
     */
    private void cancelApplyBack(WithdrawalRecord record) {

        HttpUtil.getInstance().cancelApplyBack(new CancelApplyBackRequest(record.getGUID()), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(CANCEL_ORDER_FAILED);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (result.contains("ok")){
                    handler.sendEmptyMessage(CANCEL_ORDER_SUCCEED);
                }else{
                    handler.sendEmptyMessage(CANCEL_ORDER_FAILED);
                }
            }
        });
    }
}
